package com.hupan.iot.homegateway.manager;

import com.pi4j.io.gpio.*;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;

@Slf4j
@Component
@ConditionalOnProperty(name = "homegateway.hardware", havingValue = "true")
public class PiGpioManager {

    // 硬件消抖时间
    private final int HARDWARE_FILTER_MS = 1 * 1000;

    // 光敏电阻输入和led输出
    private GpioPinDigitalInput sensorInput;
    private GpioPinDigitalOutput ledOutput;

    // 上次传感器事件时间，用于消抖
    private long lastActionTime = 0;
    private Set<SensorListener> listenerSet = new HashSet<>();

    public PiGpioManager() {
        GpioController gpioController = GpioFactory.getInstance();
        this.ledOutput = gpioController.provisionDigitalOutputPin(RaspiPin.GPIO_04);
        this.sensorInput = gpioController.provisionDigitalInputPin(RaspiPin.GPIO_01);
        this.sensorInput.addListener((GpioPinListenerDigital) this::handleSensorEvent);
        log.info("listen gpio pin");
    }

    public synchronized void addSensorListener(SensorListener listener) {
        this.listenerSet.add(listener);
    }

    public void setLedPin(boolean high) {
        if(high){
            ledOutput.high();
        } else {
            ledOutput.low();
        }
    }

    private synchronized void handleSensorEvent(GpioPinDigitalStateChangeEvent event) {

        // 消抖
        long nowTime = System.currentTimeMillis();
        if ((nowTime - lastActionTime) < HARDWARE_FILTER_MS) {
            return;
        }
        lastActionTime = nowTime;

        // 通知光线变暗
        if (event.getState() == PinState.HIGH) {
            for(SensorListener listener : listenerSet){
                listener.toDark();
            }
        }
    }
}
